package page_action;

import Dao.BaseDao;
import object.User;

import java.sql.*;

public class login {
    //用于登录时检验，返回登陆成功的用户
    public static User userlogin(String utext, String upwd) {
        //登录并将id接收，0失败，1普通用户，2管理员，3用户名与密码不符
        User user = new User( 0,null,null,"0");
        try {
            //连接数据库，获得连接对象
            Connection conn = BaseDao.getConnection();
            //搭建执行环境
            Statement statement = conn.createStatement();
            //执行sql的查询语句，得到结果集
            ResultSet result = statement.executeQuery("select * from users ;");
            while (result.next()) {
                if ((utext.equals(result.getString("uid")) || utext.equals(result.getString("uname"))) &&
                        upwd.equals(result.getString("upwd"))) {
                    user.updateUid(result.getInt("uid"));
                    user.updateUname(result.getString("uname"));
                    user.updateUpwd(result.getString("upwd"));
                    if (result.getString("utype").equals("root"))
                        user.updateUtype("2");
                    else
                        user.updateUtype("1");
                    break;//查到就终止循环
                } else {
                    user.updateUtype("3");
                }
            }
            BaseDao.close(conn,statement,result);
            return user;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
